#pragma strict
////////////////////////////////////////////////////////////////////////////////////
///传送器.
////////////////////////////////////////////////////////////////////////////////////
//传送器 有效半径
var radius:float = 3;
//传送前 等待几秒.
var delayBeforeTransfer:float = 3;
//传送的目标.
var target:Transform;
//传送的目的地.
var destination:Transform;
//传送器 是否有效.
var isValid:boolean = true;

//事件,格式为 : function(tr:Transform)
var beforeTransferEventName:String = "OnBeforeTransfer";
var beforeTransferEventReceiver:GameObject;

private var sc:SphereCollider;
private var nextTransferTime:float;

function Start () {
	sc = TransformHelper.GetComponent(gameObject,SphereCollider) as SphereCollider;
	sc.isTrigger = true;
}

function OnTriggerEnter(other:Collider) {
	Transfer(other);
}
function OnTriggerExit(other:Collider){
	TransferAbort();
}

function OnDrawGizmos(){
	Gizmos.DrawIcon(transform.position,"transfer1");
	if(destination){
		Gizmos.color = Color.blue;
		Gizmos.DrawLine(transform.position,destination.position);
	}
}

function Transfer(other:Collider){
	if(isValid && target && destination){
		var tr:Transform = other.transform;
		if(beforeTransferEventReceiver){
			beforeTransferEventReceiver.SendMessage(beforeTransferEventName,tr);
		}
		yield WaitForTransfer();
		Debug.Log("开始传送");
		if(target){
			if(Vector3.Distance(transform.position,target.position) <= radius){
				target.position = destination.position;
				TransferComplete();
			}
		}else{
			TransferAbort();
		}
	}	
}
function TransferComplete(){
	target = null;
}
function TransferAbort(){
	target = null;
}

function WaitForTransfer(){
	nextTransferTime = Time.time + delayBeforeTransfer;
	while(Time.time < nextTransferTime){
		Debug.Log("剩余时间:"+ (nextTransferTime - Time.time));
		yield;
	}
}